<?php
namespace Backend\Controllers;

use Backend\Libraries\HashNode;
use Commons\Http;
use Commons\Jwt;
use Backend\Models\Sys\Role;
use Backend\Models\Sys\User;

class IndexController extends BaseController
{

    private $arr = [];
    private $size = 10;

    public function initialize()
    {
        parent::initialize();
    }

    public function indexAction()
    {
        $a = hexdec('1') * 256 * 256 * 256;
        echo $a."<pre>";
        echo 1 << 24;
        //        $date     = date('Y-m-d-H-i-s');
        //        $date     = explode('-', $date);
        //        $date[0]  = mb_substr($date[0], -2, 2);
        //        $dateline = array_reverse(array_slice($date, 0, 3));
        //        $time     = array_slice($date, 3, 3);
        //        $string   = implode(' ', $dateline) . ' ' . implode(' ', $time);
        //        //echo 1;
        //        echo $string;
        //        //var_dump($string);
        //        exit;
        //        $this->arr = new \SplFixedArray($this->size);
        //        for ($i = 0; $i < 15; $i++) {
        //            $this->set('key' . $i, 'value' . $i);
        //        }
        //        echo "<pre>";
        //        var_dump($this->get('key3'));
        //        $this->editSize(15);
        //        for ($i = 0; $i < 15; $i++) {
        //            $this->set('key' . $i, 'value' . $i);
        //        }
        //        var_dump($this->getList());
    }

    private function simpleHash($key)
    {
        $asciiTotal = 0;
        $len        = strlen($key);
        for ($i = 0; $i < $len; $i++) {
            $asciiTotal += ord($key[$i]);
        }
        return $asciiTotal % $this->size;
    }

    public function set($key, $value)
    {
        $hash = $this->simpleHash($key);
        if (isset($this->arr[$hash])) {
            $newNode = new HashNode($key, $value, $this->arr[$hash]);
        } else {
            $newNode = new HashNode($key, $value, null);
        }
        $this->arr[$hash] = $newNode;
        return true;
    }

    public function get($key)
    {
        $hash    = $this->simpleHash($key);
        $current = $this->arr[$hash];
        while (!empty($current)) {
            if ($current->key == $key) {
                return $current->value;
            }
            $current = $current->nextNode;
        }
        return null;
    }

    public function getList()
    {
        return $this->arr;
    }

    public function menuAction()
    {
        $user = $this->getUserFromJwt();
        if ($user === false) {
            return $this->json([
                'code' => 30001,
                'msg'  => '获取角色菜单失败，请登录后再试~'
            ]);
        }
        $role   = new Role();
        $result = $role->get($user->role);
        if ($result === false || !isset($result['view'])) {
            return $this->json([
                'code' => 201,
                'msg'  => '获取角色菜单失败，请稍候再试~'
            ]);
        }
        if ($result['status'] != 1) {
            return $this->json([
                'code' => 301,
                'msg'  => '此角色已被禁用，如需启用，请与超级管理员联系~'
            ]);
        }
        $view = json_decode($result['view'], true);
        foreach ($view as $index => $item) {
            if ($item['url'] == '/me') {
                unset($view[$index]);
                break;
            }
        }
        return $this->json([
            'code' => 200,
            'data' => array_values($view)
        ]);
    }

    /**
     * @throws \Exception
     */
    public function signAction()
    {
        $account  = $this->request->get('account');
        $password = $this->request->get('password');
        if ($account == '') {
            return $this->json([
                'code' => 501,
                'msg'  => '请输入登录名~'
            ]);
        }
        if ($password == '') {
            return $this->json([
                'code' => 501,
                'msg'  => '请输入密码~'
            ]);
        }
        $user = (new User())->getByAccount($account);
        if ($user === false) {
            return $this->json([
                'code' => 401,
                'msg'  => '没有找到此账户~'
            ]);
        }
        if ($user['password'] != md5($password)) {
            return $this->json([
                'code' => 402,
                'msg'  => '密码错误~'
            ]);
        }
        if ($user['status'] != 1) {
            return $this->json([
                'code' => 503,
                'msg'  => '对不起，你已禁止登录~'
            ]);
        }
        return $this->json([
            'code'          => 200,
            'msg'           => '您已成功登录~',
            'name'          => $user['name'],
            'jwt'           => (new Jwt())->encode([
                'uid'        => $user['uid'],
                'role'       => $user['role_id'],
                'iss'        => trim($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']),
                'iat'        => time(),
                'expires_in' => 3600
            ]),
            'refresh_token' => (new Jwt())->sign([
                'uid'  => $user['uid'],
                'role' => $user['role_id']
            ])
        ]);
    }

    public static function gpsToBaiDuMap($arr)
    {
        $params = '';
        foreach ($arr as $_k => $_v) {
            $params = $params . trim($_v) . ';';
        }
        $params = rtrim($params, ';');
        $api    = 'http://api.map.baidu.com/geoconv/v1/?coords=%s&from=1&to=5&ak=NdmCgg96HrOdtXxjy5HGywWO11RSidTh';
        $api    = sprintf($api, $params);
        $result = Http::request($api);
    }

    public function uploadAction()
    {
        return $this->json(['code' => 200, 'image' => 'http://img.zcool.cn/community/01d9a955496a9c0000019ae9c57f8b.jpg']);
    }
}
